(function($) {

	if( typeof(MC) == 'undefined' ){
		MC = function(){
			return
		};
	};

	MC.utils = {
			_cookie : {
				// default the expiration date is one year from current
				currentDate : new Date(),
				calcExpiration : function( current ){
					var expiration = new Date();
					expiration.setTime( current.getTime() + 1000 * 60 * 60 * 24 * 365 )			
					return expiration
				},
				set : function( name , value ){
					document.cookie = name + "=" + value + "; expires=" + MC.utils._cookie.calcExpiration( MC.utils._cookie.currentDate ) + "; path=/";
					return
				},
				get : function( name ){
					var cookies = document.cookie.split(";"),
						cookiesLength = cookies.length;
						cookieName = name+"="
					for ( var i = 0; i < cookiesLength; i++ ){
						//console.log( cookies[i] );
						if( cookies[i].trim().indexOf(cookieName) == 0 ){
							MC.storeLocator.locationValues = $.parseJSON(cookies[i].trim().slice( cookieName.length ))
						}
					}
					return MC.storeLocator.locationValues;
				}				
			},
			
			//Tests for empty object
			_isEmpty : function( obj ){
				for( var i in obj ){ return false };
				return true
			},
			
			// _RemoveArrayItem
			// remove the second item from the array - array.remove( 1 );
			// remove the second-to-last item from the array - array.remove( -2 );
			// remove the last and second-to-last items from the array - array.remove( -2 ,-1 );
			_RemoveArrayItem : function( array , from , to ){
				var rest = array.slice((to || from) + 1 || array.length);
				array.length = from < 0 ? array.length + from : from;
				return array.push.apply( array , rest );
			}

	};


	/* BEGIN MC.updateSPUMessage
	 * updates eligibility message and store selector link
	 */

	MC.updateSPUMessage = function( ev ){

		/*
		 * relies on MC.updateSPUMessage.init
		 */
		
		var link = this.updateSPUMessage.link,
			message = this.updateSPUMessage.message,
			messageContainer = this.updateSPUMessage.messageContainer,
			href = $(link).attr("href"),
			sku,
			elig;
		
		$.each( ev.target.getSPUEligibility() , function( key , value ){
			if ( key == "sku" ){
				sku =  value.toString();
			} else if ( key == "spuElig" ){
				elig = ( value != undefined ) ? value.toString() : undefined;
			}
		});
		
		if( elig == undefined && $(messageContainer).attr("data-type-ispu-sku") == sku ){	
			updateMessageContainer( { uSku : sku , uElig : false } );
			updateMessageText( message , sku );
		};

		if ( $(messageContainer).attr("data-type-ispu-sku") != sku ){
			updateMessageContainer( { uSku : sku } );	
			if( $(messageContainer).attr("data-type-ispu-elig") != elig ) {	
				if( elig == undefined ){
					updateMessageContainer( { uElig : false } );
				} else {
					updateMessageContainer( { uElig : elig } );
					updateMessageText( message , sku );
				};
			};
			
		};

		function updateMessageContainer( update ){
			if( update.uSku != undefined ){ $(messageContainer).attr( "data-type-ispu-sku" , update.uSku ) };
			if( update.uElig != undefined ){ $(messageContainer).attr( "data-type-ispu-elig" , update.uElig ) }
				else if ( update.uElig == false )  { $(messageContainer).attr( "data-type-ispu-elig" , "false" ) };
		};
	
		function updateMessageText( obj , sku ){
			var html = $(obj).html().trim(),
				cssClass = $(obj).parent("li").attr("class");
			$(obj).html( $(obj).attr("data-type-ispu-message") ).attr( "data-type-ispu-message" ,  html );
			$(obj).parent().attr( "class" , $(obj).parent().attr("data-type-ispu-alt-class") ).attr( "data-type-ispu-alt-class" , cssClass );
			( $(obj).parent().attr("data-type-ispu-elig") == "true" && $(link).attr("data-type-default-show-link") == "true" ) ? updateLink("show" , sku ) : updateLink();
		};
		
		function updateLink( show , sku ){		
			( show == "show") ? updateLinkHref(sku , function(){ $(link).fadeIn(450).addClass("active") } ) : $(link).fadeOut(250).removeClass("active");
		};

		function updateLinkHref( sku , callback ){
			// search for these -
				// ProductSKU=
				// &SKU=
			var oldsku = href.slice( href.indexOf("ProductSKU=") + 11 , href.indexOf("&SKU=") );
				newHref = href.replace( new RegExp( oldsku, 'g') , sku );
			$(link).attr("href" , newHref );
			$(link).attr("qtyElement" , 'Quantity_'+sku );			
			//callback
			return callback ? callback.apply() : false
		};

	};
	
	MC.updateSPUMessage.getMessageElements = function( callback ){
		MC.updateSPUMessage.messageContainer = $("div.availability-messaging ul li.mc-ispu");	
		MC.updateSPUMessage.message = $(MC.updateSPUMessage.messageContainer).children("span");
		MC.updateSPUMessage.link = $(MC.updateSPUMessage.messageContainer).children("a");
		return callback ? callback.apply() : false
	};

	/* get eligibility added to KOR - kor.product.js */
	KOR.Product.prototype.getSPUEligibility = function(){
		return { spuElig : this.getCartableProductVariant() ? this.getCartableProductVariant().spuEligibility: undefined , sku : this.getBestVariantSKU() }
	};		

	/* observer added to KOR - kor.product-view.js */
	KOR.ProductView.prototype.registerObservers = KOR.ProductView.prototype.registerObservers.overload( function(){
		this._super.apply( this , arguments );
		this.observe('changeAttributeComplete', this.changeAttributeCompleteSPUEligibilityHandler, this )
	});	
	
	/* handlers added to KOR - kor.product-view.js */
	KOR.ProductView.prototype.changeAttributeCompleteSPUEligibilityHandler = function( ev ){
		if( MC.updateSPUMessage ){
			MC.updateSPUMessage.getMessageElements( function(){ MC.updateSPUMessage( ev ) });
		}
	};
	
	/* END MC.updateSPUMessage */

	
	MC.storeLocator = {
		locationValues : {},
		getValues : function(){
			return '{ "StoreSelectorForm_SearchTextField" : "' + $('#StoreSelectorForm_SearchTextField').val() + '" , ' +			
			'"StoreSelectorForm_Latitude" : "' + $('#StoreSelectorForm_Latitude').val() + '" , ' +
			'"StoreSelectorForm_Longitude" : "' + $('#StoreSelectorForm_Longitude').val() + '" }'								
		},
		setLocationValues : function(jsonObj){
			$.each( jsonObj , function( key, value ){
				if ( $(key) ){
					$('#'+key).val( value );
				}
			})
		},

		storeSearchFormAction : function( id ){
			return $("#" + id ).attr("action")
		},

		getLatLong : function( nextFunction ){
			if ($("#AdvancedSearch").val()=='false') {
					$("#StoreSelectorForm_Latitude").val(null);
					$("#StoreSelectorForm_Longitude").val(null);
					nextFunction();
			} else {
				geocoder = new google.maps.Geocoder();			
				 geocoder.geocode( { 'address' : $("#StoreSelectorForm_SearchTextField").val() }, function(results, status) {
				      if (status == google.maps.GeocoderStatus.OK) {
				    	    $("#StoreSelectorForm_Latitude").val(results[0].geometry.location.lat());
							$("#StoreSelectorForm_Longitude").val(results[0].geometry.location.lng());
							$("#StoreSelectorForm_PostalCode").val('');
							for(xx=0;xx<results[0].address_components.length;xx=xx+1){
								if (results[0].address_components[xx].types[0]=='postal_code') {
									$("#StoreSelectorForm_PostalCode").val(results[0].address_components[xx].long_name);									
								}
							}
							nextFunction();
				      } else {
				        alert("Geocode was not successful for the following reason: " + status);
				      }
				    });
			}
		},
		getNextStoreLocations : function(){			
			$("#StoreSelectorForm_PageIndex").val(Number($("#StoreSelectorForm_PageIndex").val())+Number($("#StoreSelectorForm_PageSize").val()));
			MC.storeLocator.getStoreLocations();
		},
		getPrevStoreLocations : function(){
			var prevIndex = Math.max(0,Number($("#StoreSelectorForm_PageIndex").val())-Number($("#StoreSelectorForm_PageSize").val()));			
			$("#StoreSelectorForm_PageIndex").val(prevIndex);
			MC.storeLocator.getStoreLocations();
		},
		getStoreLocations : function(){
			$.ajax({
				type: "GET",
				
				url: MC.storeLocator.requestStores( $("#search-stores").attr("action") ),
				dataType: "html",				
				success: function( html  ){
					$("#store-results").html( html )
				}
			});
		},
		requestStores : function( baseURL ){
			var storeDistance = "?StoreSelectorForm_Distance="+ $("#StoreSelectorForm_Distance").val() +"",
			storeDistanceUnit = "&StoreSelectorForm_DistanceUnit="+ $("#StoreSelectorForm_DistanceUnit").val() +"",
			searchField = "&StoreSelectorForm_SearchTextField="+ $("#StoreSelectorForm_SearchTextField").val() +"",
			postalCode = "&StoreSelectorForm_PostalCode="+$("#StoreSelectorForm_PostalCode").val()+"",
			local = "&StoreSelectorForm_Locale="+ $("#StoreSelectorForm_Locale").val() +"",
			lat = "&StoreSelectorForm_Latitude="+ $("#StoreSelectorForm_Latitude").val() +"",
			long = "&StoreSelectorForm_Longitude="+ $("#StoreSelectorForm_Longitude").val() +"",
			pageIndex = "&StoreSelectorForm_PageIndex="+ $("#StoreSelectorForm_PageIndex").val() +"",
			partner = "&StoreSelectorForm_Partner="+ $("#StoreSelectorForm_Partner").val() +"",
			pageSize = "&StoreSelectorForm_PageSize="+ $("#StoreSelectorForm_PageSize").val() +"",
			productSKU= "&ProductSKU="+$("#StoreSelectorForm_ProductSKU").val() + "",		
			lineItem = "&ProductLineItemUUID="+$("#ProductLineItemUUID").val()+"",
			quantity = "&StoreSelectorForm_Quantity=" + $("#StoreSelectorForm_Quantity").val() + "",
			jumpTarget= "&JumpTarget=ViewStoreSelector-FindStores",
			configPagelet= "&ConfigurationPageletUUID="+$("#ConfigurationPageletUUID").val()+"",			
			findStores = "&FindStores=+Find+Stores+";
			return baseURL + storeDistance + storeDistanceUnit + searchField + postalCode+ local + lat + long + pageIndex + partner + pageSize + lineItem + quantity + jumpTarget + productSKU + configPagelet+ findStores;
		},
		
		requestedQuantity: "1",
		
		loadCookies: function(){
			
			$(document).ajaxComplete( function() {
				if ($("#cookies-loaded").val()=='false') {
					$("#cookies-loaded").val('true');
					MC.utils._cookie.get( "MC");
					MC.storeLocator.setLocationValues(MC.storeLocator.locationValues);
					if ($("#StoreSelectorForm_SearchTextField").val()!='' && $("#PerformAutoSearch").val()=='true') {
						MC.storeLocator.getStoreLocations();
					}
				}
			}) }

	};



	MC.behaviors = function(){
		$("#cookies-loaded").val('false');
		MC.storeLocator.loadCookies();
		$(document).delegate( "a.find" , "click" , function() { 
			 MC.storeLocator.getLatLong( function() {
		        MC.utils._cookie.set( "MC" , MC.storeLocator.getValues() );
		        MC.storeLocator.getStoreLocations();
			 })
		});
	};
	
	MC.modifySelectStorePopupLinkForQuantity = function(linkElement) {
		var href = $('#'+linkElement).attr('href');
		var qtyElement = $('#'+linkElement).attr('qtyElement');
		var qty = $('#'+qtyElement).val();
		var oldleftSide=href.substring(0,href.indexOf("Quantity=") + 9);
		var remainingQty = href.indexOf("&",href.indexOf("Quantity=") + 9);
		var oldRight="";
		if (remainingQty>-1) {
				oldRight=href.substring(remainingQty);
		}
		var	newHref = oldleftSide+qty+oldRight;
		$('#'+linkElement).attr('href',newHref);
	}


})(jQuery);

MC.behaviors();